<template>
  <div>
    <div class="wrap">
      <h1>登录账号</h1>
      <p class="xia">虾米-严选商城欢迎您</p>
      <van-form>
        <van-field
          v-model="username"
          name="手机号码"
          label="手机号码"
          placeholder="手机号码"
          :rules="[{ required: true, message: '请填写手机号码' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" @click="doLogin">登录</van-button>
        </div>
      </van-form>
      <a>忘记密码</a>
      <br />
      <a>还没有注册？立即注册</a>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },
  beforeRouteEnter(to, from, next) {
    let data = localStorage.getItem("shuju");
    if (data == null) {
      next();
    } else {
      next("/");
    }
  },
  created() {},
  mounted() {},
  methods: {
    //执行登陆的操作
    doLogin() {
      if (this.username == "" || this.password == "") {
        this.$toast.fail("用户名或密码不能为空");
        return false;
      }

      let patt = /^1[34578]\d{9}$/; //手机号的正则
      if (patt.test(this.username) == false) {
        this.$toast.fail("手机号不正确,请重新输入");
        return false;
      }

      let formdata = new FormData();

      formdata.append("mobile", this.username);
      formdata.append("pwd", this.password);

      this.$axios
        .post(
          "https://api.it120.cc/small4/user/m/login?deviceId=007&deviceName=monkey",
          formdata
        )
        .then((res) => {
          if (res.code != 0) {
            this.$toast.fail(res.msg);
            return false;
            console.log(res)
          }
          res.data.username = this.username;
          localStorage.setItem("shuju", JSON.stringify(res.data));

          this.$router.go(-1);
          console.log(res);
        });
    },
  },
};
</script>

<style scoped lang="less">
.wrap {
  text-align: center;
  width: 7rem;
  height: 12rem;
  border: 0.02rem solid #ccc;
  margin: 0.2rem 0.2rem 0 0.2rem;
  h1 {
    font-size: 0.3rem;
    margin: 0.52rem 0 0.5rem 0.44rem;
  }
  .xia {
    font-size: 0.2rem;
    margin-left: 0.44rem;
    margin-bottom: 0.48rem;
  }
  a {
    font-size: 0.2rem;
  }
}
</style>
